<?php

namespace app\admin\controller\cms;
use app\admin\controller\Base;
use think\facade\Request;
use think\facade\View;
use think\facade\Db;

class Category extends Base
{
    protected $categorys;
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\cms\Category;
        // 栏目选择列表
        $categorys = $this->model->select()->toArray();
        foreach ($categorys as $key => $value) {
            $this->categorys[$value['id']] = $value;
        }
        $this->categorys = cateTree($categorys);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $option = [
                'order' => 'pid asc,sort asc',
                'page' => false
            ];
            $list = $this->model->loadList($option);
            if ($list['result'] == 'success'){
                foreach($list['list'] as $k=>$v){
                    $list['list'][$k]['lay_is_open']=true;
                }
                $result = ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['list']];
            }else{
                $result = ['code' => 0, 'msg' => $list['msg'], 'data' => [], 'count' => 0];
            }
            return $result;
        }
        return view();
    }
    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        $parentid = input('param.parentid');

        $view = [
            'info' => '',
            'categorys' => $this->categorys,
            'parentid' => $parentid,
        ];
        View::assign($view);
        return view();
    }
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $this->request->post();

        $data['child'] = isset($data['child'])?1:0;
        Db::startTrans();
        try{
            $id = $this->model::insertGetId($data);
            $this->repair();
            $this->repair();
            
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('栏目添加成功!',url('index'));
        
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $info = $this->model::where('id',$id)->find();
        $view = [
            'info' => $info,
            'categorys' => $this->categorys
        ];
        View::assign($view);
        return view();
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $data = $this->request->post();
        $data['arrparentid'] = $this->get_arrparentid($data['id']);
        $data['child'] = isset($data['child']) ? '1' : '0';
        if (false !==$this->model::update($data)) {
            if($data['child']==1){
                $arrchildid = $this->get_arrchildid($data['id']);
                $data2['ismenu'] = $data['ismenu'];
                $data2['pagesize'] = $data['pagesize'];
                $this->model::where( ' id in ('.$arrchildid.')')->update($data2);
            }
            $this->repair();
            $this->repair();
            $this->success('栏目修改成功!',url('index'));
        } else {
            $this->error('栏目修改失败!');
        }
    }
    public function repair() {
        @set_time_limit(500);
        
        $categorys =  $this->model::where("pid=0")->order('sort ASC,id ASC')->select()->toArray();
        $this->set_categorys($categorys);
        
        if(is_array($this->categorys)) {
            foreach($this->categorys as $id => $cat) {

                if($id == 0) continue;
                $this->categorys[$id]['arrparentid'] = $arrparentid = $this->get_arrparentid($id);
                $this->categorys[$id]['arrchildid'] = $arrchildid = $this->get_arrchildid($id);
                $this->categorys[$id]['parentdir'] = $parentdir = $this->get_parentdir($id);
                $this->model::update(array('parentdir'=>$parentdir,'arrparentid'=>$arrparentid,'arrchildid'=>$arrchildid,'id'=>$id));
            }
        }

    }
    public function set_categorys($categorys = array()) {
        if (is_array($categorys) && !empty($categorys)) {
            foreach ($categorys as $id => $c) {
                $this->categorys[$c['id']] = $c;
                $r = $this->model::where(array("pid"=>$c['id']))->Order('sort ASC,id ASC')->select();
                $this->set_categorys($r);
            }
        }
        return true;
    }
    public function get_arrparentid($id, $arrparentid = '') {
        if(!is_array($this->categorys) || !isset($this->categorys[$id])) return false;
        $parentid = $this->categorys[$id]['pid'];
        $arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
        if($parentid) {
            $arrparentid = $this->get_arrparentid($parentid, $arrparentid);
        } else {
            $this->categorys[$id]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }
    public function get_arrchildid($id) {
        $arrchildid = $id;
        if(is_array($this->categorys)) {
            foreach($this->categorys as $catid => $cat) {
                if($cat['pid'] && $id != $catid) {
                    $arrparentids = explode(',', $cat['arrparentid']);
                    if(in_array($id, $arrparentids)){
                        $arrchildid .= ','.$catid;
                    }
                }
            }
        }
        return $arrchildid;
    }
    public function get_parentdir($id) {
        if($this->categorys[$id]['pid']==0){
            return '';
        }
        $arrparentid = $this->categorys[$id]['arrparentid'];
        unset($r);
        if ($arrparentid) {
            $arrparentid = explode(',', $arrparentid);
            $arrcatdir = array();
            foreach($arrparentid as $pid) {
                if($pid==0) continue;
                $arrcatdir[] = $this->categorys[$pid]['catdir'];
            }
            return implode('/', $arrcatdir).'/';
        }
    }
}
